package DAO;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

public class BaseDao {
    public static String driver;
    public static String url;
    public static String username;
    public static String password;
    public static Connection con;

    static {
        into();
    }

    public static void into() {
        //创建对象
        Properties p = new Properties();
        //读取文件
        InputStream inputS = BaseDao.class.getClassLoader().getResourceAsStream("database.properties");
        try {
            p.load(inputS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        driver = p.getProperty("driver");
        url = p.getProperty("url");
        username = p.getProperty("username");
        password = p.getProperty("password");
    }

    public void getBeat() {
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static void map(Map<String, String> map, Object o) throws IllegalAccessException, ParseException {
        Class<?> clazz = o.getClass();//1.获取Class接口
        Field[] fields = clazz.getDeclaredFields();//2.获取所有声明的属性（包括：公有，私有）
        for (Field field : fields) {
            field.setAccessible(true);//暴力反射
            String name = field.getType().getTypeName();
            if (null != map.get(field.getName())) {
                if ("java.lang.Long".equals(name)) {
                    Long longV = Long.valueOf(map.get(field.getName()));
                    //3.给目标对象 设置 Set方法  第一个参数： 目标参数   第二的参数： 设置的值
                    field.set(o,longV);
                }else if ("java.math.BigDecimal".equals(name)) {
                    BigDecimal bigDecimal =new BigDecimal(map.get(field.getName())); ;
                    field.set(o,bigDecimal);
                }else if ("java.util.Date".equals(name)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = sdf.parse(map.get(field.getName()));
                    field.set(o,date);
                }else {
                    //反射api,将map的值设置到对象中
                    field.set(o,map.get(field.getName()));
                }
            }
        }
    }
}
